import 'dotenv/config';
import { themes as prismThemes } from 'prism-react-renderer';
import type { Config } from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
import type { ScalarOptions } from '@scalar/docusaurus';


const CDN_PREFIX = process.env.DOCS_CDN_PREFIX;
const SITE_URL = process.env.DOCS_SITE_URL;
envCheck();

const config: Config = {
  title: 'MoArk',
  tagline: 'Building AI Applications Made Simple',
  favicon: `${CDN_PREFIX}/img/favicon.ico`,

  // Set the production url of your site here
  url: SITE_URL,
  // Set the /<baseUrl>/ pathname under which your site is served
  // For GitHub pages deployment, it is often '/<projectName>/'
  baseUrl: '/docs/',

  // GitHub pages deployment config.
  // If you aren't using GitHub pages, you don't need these.
  organizationName: 'gitee-ai', // Usually your GitHub org/user name.
  projectName: 'docs', // Usually your repo name.

  onBrokenLinks: 'throw',
  onBrokenMarkdownLinks: 'warn',

  // Even if you don't use internationalization, you can use this field to set
  // useful metadata like html lang. For example, if your site is Chinese, you
  // may want to replace "en" with "zh-Hans".
  i18n: {
    defaultLocale: 'zh-Hans',
    locales: ['zh-Hans'],
  },

  presets: [
    [
      'classic',
      {
        docs: {
          routeBasePath: '/',
          sidebarPath: './sidebars.ts',
          // Please change this to your repo.
          // Remove this to remove the "edit this page" links.
          editUrl: 'https://gitee.com/moark/docs/edit/main/',
          editLocalizedFiles: true,
        },
        blog: {
          showReadingTime: true,
          // Please change this to your repo.
          // Remove this to remove the "edit this page" links.
          editUrl: 'https://gitee.com/moark/docs/edit/main/',
          editLocalizedFiles: true,
        },
        theme: {
          customCss: './src/css/custom.css',
        },
      } satisfies Preset.Options,
    ],
  ],

  themeConfig: {
    // Replace with your project's social card
    // image: 'img/docusaurus-social-card.jpg',
    navbar: {
      // title: 'Gitee AI',
      logo: {
        alt: 'moark logo',
        src: `${CDN_PREFIX}/img/logo-full.svg`,
        srcDark: `${CDN_PREFIX}/img/logo-full-white.svg`,
        href: SITE_URL,
        target: '_self',
        style: {
          paddingLeft: '8px',
        },
      },
      items: [
        {
          type: 'html',
          position: 'left',
          className: 'gai-navbar-item-home',
          value: `<a href="${SITE_URL}" target="_self">工作台</a>`,
        },
        {
          label: '模型广场',
          to: `${SITE_URL}/serverless-api`,
          target: '_self',
          className: 'gai-navbar-item gai-navbar-item-badge',
        },
        {
          label: 'AI 应用市场',
          to: `${SITE_URL}/appstore`,
          target: '_self',
          className: 'gai-navbar-item',
        },
        {
          label: '模型下载',
          items: [
            {
              label: '模型下载',
              to: `${SITE_URL}/models`,
              target: '_self',
            },
            {
              label: '数据集下载',
              to: `${SITE_URL}/datasets`,
              target: '_self',
            },
          ],
        },
        {
          label: '解决方案',
          items: [
            {
              label: '模型引擎',
              to: `${SITE_URL}/solutions/model-engine`,
              target: '_self',
            },
            {
              label: '应用引擎',
              to: `${SITE_URL}/solutions/app-engine`,
              target: '_self',
            },
            {
              label: 'GiEngine 高速推理引擎',
              to: `${SITE_URL}/solutions/serverless`,
              target: '_self',
            },
            {
              label: '分布式算力网络',
              to: `${SITE_URL}/solutions/computing-network`,
              target: '_self',
            },
            {
              label: '模型微调服务',
              to: `${SITE_URL}/solutions/training`,
              target: '_self',
            },
          ],
        },
        {
          label: '专区',
          items: [
            {
              label: '昇腾计算',
              to: `${SITE_URL}/topics/ascend`,
              target: '_self',
            },
            {
              label: '昇腾 AI 开发板',
              to: `${SITE_URL}/topics/ascend-edge`,
              target: '_self',
            },
            {
              label: '天数智芯',
              to: `${SITE_URL}/topics/iluvatar`,
              target: '_self',
            },
            {
              label: '沐曦',
              to: `${SITE_URL}/serverless-api/packages/1492`,
              target: '_self',
            },
            {
              label: '科华（壁仞）',
              to: `${SITE_URL}/serverless-api/packages/2018`,
              target: '_self',
            },
            {
              label: '燧原',
              to: `${SITE_URL}/serverless-api/packages/2057`,
              target: '_self',
            },

            {
              label: '国产大模型',
              to: `${SITE_URL}/topics/domestic`,
              target: '_self',
            },
            {
              label: 'AI 编程',
              to: `${SITE_URL}/topics/ai`,
              target: '_self',
            },
          ],
        },
        {
          label: '文档',
          to: `/docs/`,
          className: 'gai-navbar-item',
          activeBaseRegex: '^/docs.*',
        },
        {
          type: 'localeDropdown',
          position: 'right',
        },
      ],
    },
    footer: {
      style: 'light',
      /*
            links: [
              {
                title: 'Docs',
                items: [
                  {
                    label: 'Tutorial',
                    to: '/docs/intro',
                  },
                ],
              },
              {
                title: 'Community',
                items: [
                  {
                    label: 'Stack Overflow',
                    href: 'https://stackoverflow.com/questions/tagged/docusaurus',
                  },
                  {
                    label: 'Discord',
                    href: 'https://discordapp.com/invite/docusaurus',
                  },
                  {
                    label: 'Twitter',
                    href: 'https://twitter.com/docusaurus',
                  },
                ],
              },
              {
                title: 'More',
                items: [
                  {
                    label: 'Blog',
                    to: '/blog',
                  },
                  {
                    label: 'Gitee AI',
                    href: SITE_URL,
                  },
                ],
              },
            ],
            */
      copyright: `Copyright © ${new Date().getFullYear()} 模力方舟.`,
    },
    prism: {
      additionalLanguages: ['bash', 'json'],
      theme: prismThemes.github,
      darkTheme: prismThemes.dracula,
    },
    zoom: {
      selector: '.markdown img',
      config: {},
    },
    metadata: [
      {
        name: 'keywords',
        content: 'moark, gitee ai, 模力方舟, 大模型, MaaS, 模型即服务, AI 应用, AI 开发, AI 平台, AI 工具, AI 解决方案, AI 搜索, AI 数据分析'
      },
      {
        name: 'description',
        content:
          '模力方舟（Gitee AI），汇聚了最新最热的 AI 模型，提供模型体验、推理、微调和应用的一站式服务，提供了丰富的算力选择，希望帮助企业和开发者更容易地开发 AI 应用。'
      }
    ],
    colorMode: {
      defaultMode: 'light',
      disableSwitch: false,
      respectPrefersColorScheme: true
    },
  } satisfies Preset.ThemeConfig,
  plugins: [
    'docusaurus-plugin-image-zoom',
    // 添加本地搜索插件
    [
      require.resolve('@easyops-cn/docusaurus-search-local'),
      {
        // 中文搜索配置
        hashed: true,
        language: ['en', 'zh'],
        indexDocs: true,
        indexBlog: false,
        indexPages: false,
        docsRouteBasePath: '/',
        // 搜索结果数量限制
        searchResultLimits: 8,
        // 搜索上下文长度
        searchResultContextMaxLength: 50,
        // 启用搜索建议
        explicitSearchResultPath: true,
        // 支持中文分词
        searchBarShortcut: true,
        searchBarShortcutHint: true,
        // 搜索栏位置
        searchBarPosition: 'right',
        // 不索引调试构建
        ignoreFiles: [/\/build\//, /\/node_modules\//],
      },
    ],
    // 添加自定义加载效果插件
    require('./src/plugins/scalar-loading-plugin'),
    // 添加简单的环境变量替换插件（只处理 .md 文件）
    require('./src/plugins/simple-env-replacement-plugin'),
    // 添加 MDX 环境变量替换插件（处理 .mdx 文件）
    require('./src/plugins/mdx-env-replacement-plugin'),
    [
      '@scalar/docusaurus',
      {
        id: 'openapi/v1',
        label: '接口文档',
        route: `/docs/openapi/v1`,
        showNavLink: false,
        configuration: {
          url: `${SITE_URL}/v1/yaml`,
          // url: `/docs/test.yml`, // 本地测试
          servers: [
            {
              url: `${SITE_URL}/v1`,
              description: '生产服务器',
            },
          ],
          defaultOpenAllTags: true,
          hideClientButton: true,
          hideModels: true,
          documentDownloadType: 'none',
        },
        cdn: `${CDN_PREFIX}/@scalar/api-reference@1.32.5.js`,
      } as ScalarOptions,
    ],
    function () {
      return {
        name: 'cdn-image-plugin',
        configureWebpack(config, isServer) {
          return {
            output: {
              publicPath: `${CDN_PREFIX}/`, // 将静态资源的路径指向 CDN
            },
          };
        },
      };
    },
  ],
  ssrTemplate: `<!DOCTYPE html>
<html <%~ it.htmlAttributes %>>
  <head>
    <meta charset="UTF-8">
    <meta name="generator" content="Docusaurus v<%= it.version %>">
    <% it.metaAttributes.forEach((metaAttribute) => { %>
      <%~ metaAttribute %>
    <% }); %>
    <%~ it.headTags %>
    <% it.stylesheets.forEach((stylesheet) => { %>
      <link rel="stylesheet" href="${CDN_PREFIX}/<%= stylesheet %>" />
    <% }); %>
    <% it.scripts.forEach((script) => { %>
      <script src="${CDN_PREFIX}/<%= script %>" defer></script>
    <% }); %>
  </head>
  <body <%~ it.bodyAttributes %>>
    <%~ it.preBodyTags %>
    <div id="__docusaurus"><%~ it.appHtml %></div>
    <%~ it.postBodyTags %>
  </body>
</html>`,
};

export default config;

function envCheck() {
  if (!CDN_PREFIX || !SITE_URL) {
    const tips = 'CDN_PREFIX or SITE_URL environment variable does not exist';
    console.log();
    console.log();
    console.log(tips);
    console.log();
    throw new Error(tips);
  }
}
